/*
  这个文件是API接口调用
  引用库：crypto加密库，q对象库
 */
var crypto = require("./crypto.js");
var q = require("./q.js");
var config = require("./config.js");

/**
 * 对象覆盖$.extend函数简化版
 */
var extend = function (defaults, params) {
    for (var i in params) {
        defaults[i] = params[i];
    }
    return defaults;
};

/**
 * API请求
 */
var apiRequest = function (method, url, params) {
    var _q = q.defer();
    var type = (method == "POST") ? "application/x-www-form-urlencoded" : 'text/html';
    wx.request({
        url: url,
        method: method,
        data: params,
        header: {
          'Content-Type': type
        },
        //请求成功
        success: function (res) { 
          _q.resolve(res.data); 
        },
        //请求失败
        fail: function (err) { 
          _q.reject(err); 
        },
        //请求完成后执行的函数
        complete: function () { 
          _q.notify(1); 
        }
    });
    //promis的方法有：
    //then(successCallback, errorCallback, notifyCallback)
    //finally：都会执行
    return _q.promise;
}

/**
 * API GET 请求
 */
var apiGet = function (url, params) {
    return apiRequest("GET", url, params);
}

/**
 * * API POST 请求
 */
var apiPost = function (url, params) {
    return apiRequest("POST", url, params);
}

/**
 * 导出公开的API函数
 */
module.exports = {
    /**
     * 获取API URL
     * type：传入API名称，如：GetChannel
     */
    getUrl: function (type) {
      var OtherParams = '?' + config.Api.DebugParams;
      var UrlPrefix = config.Api.WebUrl + config.Api.InstallDir + '/index.php/api/';
        var apiUrl = UrlPrefix + type + OtherParams;
        return apiUrl;
    },

    /**
     * 获取API后端网址
     */
    getWebUrl:function(){
      return config.Api.WebUrl;
    },

    /**
     * 根据传入的参数，获取参数签名
     * params: api相关参数
     */
    getSign: function (params) {
        var sign = "";
        var signTemp = "";
        var temp = {};
        //过滤参数
        for (var key in params) {
            if (params[key] !== '' && params[key] !== undefined) temp[key] = params[key];
        }

        //排序，链接字符串
        var keys = Object.keys(temp).sort();
        var paramsString = '';
        for (var i = 0; i < keys.length; i++) {
            if (i > 0) paramsString += '&';
            //paramsString += keys[i]+'='+encodeURIComponent(temp[ keys[i] ]);
            //encodeURIComponent和php的encodeUrl存在部分不一致，建议不使用encodeURIComponent
            paramsString += (keys[i] + '=' + temp[keys[i]]);
        }

        //生成链接字符串+秘钥的md5码
        signTemp = paramsString + config.Api.AppSecret;
        sign = crypto.MD5(signTemp);
        sign = String(sign);
        return sign;
    },

    /**
     * 获取所有参数（包含计算签名）
     * params：api相关参数
     * hasSign：1：计算签名，2：不计算签名；一般是提交数据时才需要获取签名
     */
    getParams: function (params, hasSign) {
        if (!params) params = {};
        params.l = this.getCurrentLanguageMark();
        params.Format = config.Api.Format;
        params.IsApi = 1;   //表示API模式调用
        params.AppID = config.Api.AppID;
        params.ClientType = config.Api.ClientType;
        //获取Unix时间戳+时间戳差，保证客户端和服务器端时间一致
        params.Timestamp = Math.round(new Date().getTime() / 1000);
        var token = wx.getStorageSync('Token') || ''; //Token为登陆令牌
        var ic = wx.getStorageSync("ic"); //邀请码
        if (ic) params.ic = ic;
        if (token) params.Token = token;
        if (hasSign) { //表示生成签名信息
            params.Sign = this.getSign(params);
        }
        return params;
    },

    /**
     * 获取当前默认的语言标识
     */
    getCurrentLanguageMark:function(){
      var LanguageMark = wx.getStorageSync('LanguageMark') || '';
      if (!LanguageMark){
        var res = wx.getSystemInfoSync();//zh_CN zh_HK zh_TW
        if ( 0 == res["language"].indexOf("zh") ){
          LanguageMark = "cn";
        }else{
          LanguageMark = "en";
        }
      }
      return LanguageMark;
    },

    /**
     * 获取频道信息
     */
    getChannel: function (params) {
        var apiUrl = this.getUrl('GetChannel');
        params = extend({
            Field: 'ChannelID,ChannelName'
        }, params);
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取信息相册
     */
    getChannelAlbum: function (params) {
        var apiUrl = this.getUrl('GetChannelAlbum');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取频道相关文章
     */
    getChannelRelation: function (params) {
        var apiUrl = this.getUrl('GetChannelRelation');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },
    SearchProblem:function(params){
      var apiUrl = this.getUrl('SearchProblem');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },
    ModifyProblem:function(params){
      var apiUrl = this.getUrl('ModifyProblem');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },
    /**
     * 查找频道
     * id: 频道ID
     */
    findChannel: function (id) {
        var apiUrl = this.getUrl('FindChannel');
        var params = { ChannelID: id };
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取频道模型属性标记
     */
    getLabel: function (params) {
        var apiUrl = this.getUrl('GetLabel');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },
    /**
     * 获取信息
     */
    getInfo: function (params) {
        var apiUrl = this.getUrl('GetInfo');
        params = extend({
            Field: 'InfoID,InfoTitle,InfoSContent,InfoPicture,InfoHit,f1,f2',
            // NowPage: 1
        }, params);
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 查找信息
     * id: 信息ID
     */
    findInfo: function (id) {
        var apiUrl = this.getUrl('FindInfo');
        var params = { id: id };
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取信息相册
     */
    getInfoAlbum: function (params) {
        var apiUrl = this.getUrl('GetInfoAlbum');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取相关文章
     */
    getInfoRelation: function (params) {
        var apiUrl = this.getUrl('GetInfoRelation');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取专题
     */
    getSpecial: function (params) {
        var apiUrl = this.getUrl('GetSpecial');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取幻灯片
     */
    getBanner: function (params) {
        var apiUrl = this.getUrl('GetBanner');
        params = extend({
            BannerGroupID: -1,
        }, params);
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取广告
     */
    getAd: function (params) {
        var apiUrl = this.getUrl('GetAd');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取区域信息
     */
    getArea: function (params) {
        var apiUrl = this.getUrl('GetArea');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取广告分组
     */
    getAdGroup: function (params) {
        var apiUrl = this.getUrl('GetAdGroup');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取在线客服
     */
    getSupport: function (params) {
        var apiUrl = this.getUrl('GetSupport');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 人才招聘
     */
    getJob: function (params) {
        var apiUrl = this.getUrl('GetJob');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取频道模型属性
     */
    getModel: function (params) {
        var apiUrl = this.getUrl('GetModel');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     *获取评论 
     */
    getComment: function (params) {
        var apiUrl = this.getUrl('GetWXComment');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },
    GetCountTask:function(params){
      var apiUrl = this.getUrl('GetCountTask');
      params = this.getParams(params);
      return apiGet(apiUrl, params);
    },
    GetCountTaskInfo:function(params){
      var apiUrl = this.getUrl('GetCountTaskInfo');
      params = this.getParams(params);
      return apiGet(apiUrl, params);
    },
    //获取评测内容
    GetTaskInspect: function (params) {
      var apiUrl = this.getUrl('GetTaskInspect');
      params = this.getParams(params);
      return apiGet(apiUrl, params);
  },
   //开始评测
   StartTask: function (params) {
    var apiUrl = this.getUrl('StartTask');
    params = this.getParams(params);
    return apiGet(apiUrl, params);
  },
  //评测详情
  GetInspectInfo: function (params) {
    var apiUrl = this.getUrl('GetInspectInfo');
    params = this.getParams(params);
    return apiGet(apiUrl, params);
  },

    /**
     * 获取评论统计
     */
    statComment: function (params) {
        var apiUrl = this.getUrl('StatComment');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },
    /**
     * 添加评论
     * @param {array} params 
     */
    addComment:function (params) {
      var apiUrl = this.getUrl('AddComment');
      params = this.getParams(params);
      return apiGet(apiUrl, params);
    },
    /**
     * 获取幻灯分组
     */
    getBannerGroup: function (params) {
        var apiUrl = this.getUrl('GetBannerGroup');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取收藏
     */
    getFavorite: function (params) {
        var apiUrl = this.getUrl('GetFavorite');
        params = extend({
            NowPage: 1,
            PageSize: 20
        }, params);
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },
    
    /**
     * 添加收藏
     */
    addFavorite: function (params) {
        var apiUrl = this.getUrl('AddFavorite');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },
    
    /**
     * 获取阅读历史
     */
    getHistory: function (params) {
        var apiUrl = this.getUrl('GetHistory');
        params = extend({
            NowPage: 1,
            PageSize: 20
        }, params);
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },
    
    /**
     * 添加阅读历史
     */
    addHistory: function (params) {
        var apiUrl = this.getUrl('AddHistory');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },
    
    SaveInspectInfo: function (params) {
      var apiUrl = this.getUrl('SaveInspectInfo');
      params = this.getParams(params, true);
      return apiPost(apiUrl, params);
    },
    
    SaveReferenceImgTask:function(params){
      var apiUrl = this.getUrl('SaveReferenceImgTask');
      params = this.getParams(params, true);
      return apiPost(apiUrl, params);
    },
    ResetMemberPassword:function(params){
      var apiUrl = this.getUrl('ResetMemberPassword');
      params = this.getParams(params, true);
      return apiPost(apiUrl, params);
    },
    ModifyMemberPassword:function(params){
      var apiUrl = this.getUrl('ModifyMemberPassword');
      params = this.getParams(params, true);
      return apiPost(apiUrl, params);
    },
    CompleteGTask:function(params){
      var apiUrl = this.getUrl('CompleteGTask');
      params = this.getParams(params, true);
      return apiPost(apiUrl, params);
    },
    /**
     * 获取系统配置
     */
    getConfig: function (params) {
        var apiUrl = this.getUrl('GetConfig');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 登陆
     */
    login: function (params) {
        var apiUrl = this.getUrl('Login');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 微信登陆/绑定
     */
    wxLogin: function () {
      var that = this;
      var _q = q.defer();
      wx.login({
        success: function (res) {
          if (res.code) {
            wx.getUserInfo({
              success: function (data) {
                var params = {
                  code: res.code,
                  nickName: data.userInfo.nickName,
                  avatarUrl: data.userInfo.avatarUrl,
                  gender: data.userInfo.gender
                };

                var url = that.getUrl('WxLogin');
                params = that.getParams(params, true);
                wx.request({
                  url: url,
                  method: "POST",
                  data: params,
                  header: { 'Content-Type': "application/x-www-form-urlencoded" },
                  //请求成功
                  success: function (r) {
                    _q.resolve(r.data);
                  },
                  //请求失败
                  fail: function (err) {
                    var myresult = {
                      Status: 0,
                      Message: err,
                      Data: null
                    }
                    _q.resolve(myresult);
                  },
                  //请求完成后执行的函数
                  complete: function () {
                    _q.notify(1);
                  }
                });
              },
              //wx.getUserInfo失败事件
              fail: function (res) {
                var myresult = {
                  Status: 0,
                  Message: res.errMsg,
                  Data: null
                }
                _q.resolve(myresult);
              }
            });
          } else {  //获取code失败
            var myresult = {
              Status: 0,
              Message: res.errMsg,
              Data: null
            }
            _q.resolve(myresult);
          }
        },
        //wx.login失败事件
        fail: function (res) {
          var myresult = {
            Status: 0,
            Message: res.errMsg,
            Data: null
          }
          _q.resolve(myresult);
        }
      });
      return _q.promise;
    },
    
    /**
     * 自动登录
     */
    autoLogin: function (params) {
        var apiUrl = this.getUrl('AutoLogin');
        var params = {
          MemberName: params.MemberName,
          MemberPassword: params.MemberPassword,
        };
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },
    
    /**
     * 退出登陆
     */
    loginOut: function () {
        var apiUrl = this.getUrl('LoginOut');
        var params = {};
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },
    
    /**
     * 注册
     */
    reg: function (params) {
        var apiUrl = this.getUrl('Reg');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },
    
    /**
     * 忘记密码
     */
    forget: function (params) {
        var apiUrl = this.getUrl('Forget');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 修改密码
     */
    modifyPassword: function (params) {
        var apiUrl = this.getUrl('ModifyPassword');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },
    //返回联系人
    getSMember:function(params){
      var apiUrl = this.getUrl('SearchMember');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },
    /**
     * 修改个人资料
     */
    modifyMemberInfo: function (params) {
        var apiUrl = this.getUrl('ModifyMemberInfo');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    //返回国检任务
    SearchGTask: function (params) {
      var apiUrl = this.getUrl('SearchGTask');
      params = this.getParams(params, true);
      return apiPost(apiUrl, params);
    },

    /**
     * 将商品加入购物车
     */
    addCart: function (params) {
        var apiUrl = this.getUrl('AddCart');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 删除购物车商品
     */
    deleteCart: function (params) {
        var apiUrl = this.getUrl('DeleteCart');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 清空购物车
     */
    clearCart: function (params) {
        var apiUrl = this.getUrl('ClearCart');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 设置购物车商品数量
     */
    setQuantity: function (params) {
        var apiUrl = this.getUrl('SetQuantity');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 商品商量加1
     */
    incQuantity: function (params) {
        var apiUrl = this.getUrl('IncQuantity');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 商品商量减1
     */
    decQuantity: function (params) {
        var apiUrl = this.getUrl('DecQuantity');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     *获取线上优惠券(主要用户结算页面)
     */
    getCoupon: function (params) {
        var apiUrl = this.getUrl('GetCoupon');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 获取优惠券
     */
    GetCouponSend: function (params) {
      var apiUrl = this.getUrl('GetCouponSend');
      params = this.getParams(params, true);
      return apiPost(apiUrl, params);
    },

    /**
    * 删除我的优惠券
    */
    DeleteCouponSend: function (params) {
      var apiUrl = this.getUrl('DeleteCouponSend');
      params = this.getParams(params, true);
      return apiPost(apiUrl, params);
    },

    /**
     * 使用线下优惠券
     */
    useCouponCode: function (params) {
        var apiUrl = this.getUrl('UseCouponCode');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 获取积分
     */
    getPoint: function (params) {
        var apiUrl = this.getUrl('GetPoint');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 使用积分
     */
    usePoint: function (params) {
        var apiUrl = this.getUrl('UsePoint');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     *获取购物车所有商品 
     */
    getCart: function (params) {
        var apiUrl = this.getUrl('GetCart');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 获取所有收货地址
     */
    getConsignee: function (params) {
        var apiUrl = this.getUrl('GetConsignee');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 查找所有收货地址
     */
    findConsignee: function (params) {
        var apiUrl = this.getUrl('FindConsignee');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 添加收货地址
     */
    addConsignee: function (params) {
        var apiUrl = this.getUrl('AddConsignee');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 删除收货地址
     */
    deleteConsignee: function (params) {
        var apiUrl = this.getUrl('DeleteConsignee');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 保存收货地址
     */
    saveConsignee: function (params) {
        var apiUrl = this.getUrl('SaveConsignee');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 获取最后一次的收货人信息
     */
    getLatestConsignee: function (params) {
        var apiUrl = this.getUrl('GetLatestConsignee');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 设置默认的收货地址
     */
    setDefaultConsignee: function (params) {
        var apiUrl = this.getUrl('SetDefaultConsignee');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 获取默认收货地址
     */
    getDefaultConsignee: function (params) {
        var apiUrl = this.getUrl('GetDefaultConsignee');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 获取收货时间列表
     */
    getDeliveryTime: function (params) {
        var apiUrl = this.getUrl('GetDeliveryTime');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取配送信息
     */
    getShipping: function (params) {
        var apiUrl = this.getUrl('GetShipping');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取支付信息
     */
    getPay: function (params) {
        var apiUrl = this.getUrl('GetPay');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取价格范围
     */
    getPriceRange: function (params) {
        var apiUrl = this.getUrl('GetPriceRange');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取类型属性
     */
    getTypeAttribute: function (params) {
        var apiUrl = this.getUrl('GetTypeAttribute');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取已选择的属性
     */
    getSelectedAttribute: function (params) {
        var apiUrl = this.getUrl('GetSelectedAttribute');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 获取排行榜
     */
    getTop: function (params) {
        var apiUrl = this.getUrl('GetTop');
        params = this.getParams(params);
        return apiGet(apiUrl, params);
    },

    /**
     * 保存订单
     */
    saveOrder: function (params) {
        var apiUrl = this.getUrl('SaveOrder');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 提交反馈
     */
    addAppFeedback: function (params) {
        var apiUrl = this.getUrl('AddAppFeedback');
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 获取会员订单
     */
    getOrder: function (params) {
        var apiUrl = this.getUrl('GetOrder');
        params = extend({
            NowPage: 1,
            PageSize: 20
        }, params);
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 订单统计
     * 返回的数据res.Data的健就是订单状态ID，值就是相应的统计结果，如：等待付款的统计值是res.Data[1]
     * 1：等待付款、2：待发货、3：待收货、4：已退款、5：已退货、6：已完成、7：已作废、8：已取消
     */
    statOrder: function () {
        var apiUrl = this.getUrl('StatOrder');
        var params = { };
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 查找会员订单
     */
    findOrder: function (id) {
        var apiUrl = this.getUrl('FindOrder');
        var params = { OrderID: id };
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 会员删除订单
     */
    deleteOrder: function (id) {
        var apiUrl = this.getUrl('DeleteOrder');
        var params = { OrderID: id };
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 会员取消订单
     */
    cancelOrder: function (id) {
        var apiUrl = this.getUrl('CancelOrder');
        var params = { OrderID: id };
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 会员确认收货
     */
    confirmReceipt: function (id) {
        var apiUrl = this.getUrl('ConfirmReceipt');
        var params = { OrderID: id };
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 设置为已支付状态
     */
    setPayStatus: function (id) {
        var apiUrl = this.getUrl('SetPayStatus');
        var params = { OrderID: id };
        params = this.getParams(params, true);
        return apiPost(apiUrl, params);
    },

    /**
     * 小程序支付，id:订单ID
     */
    requestPayment:function(id){
        var _q = q.defer();
        var url = this.getUrl('RequestPayment');
        var params = { OrderID: id };
        params = this.getParams(params, true);
        wx.request({
            url: url,
            method: "POST",
            data: params,
            header: { 'Content-Type': "application/x-www-form-urlencoded" },
            //请求成功
            success: function (r) {
                var obj = r.data;
                if (obj.Status == 1) {
                    wx.requestPayment({
                        'timeStamp': obj.Data['timeStamp'].toString(),
                        'nonceStr': obj.Data['nonceStr'],
                        'package': obj.Data['package'],
                        'signType': obj.Data['signType'],
                        'paySign': obj.Data['paySign'],
                        'complete': function (res) {
                            if (res.errMsg == "requestPayment:ok") {
                                _q.resolve(obj);
                                
                            } else {
                                obj.Status = 0;
                                obj.Message = "支付失败";
                                obj.Data = null;
                                _q.resolve(obj);
                            }
                        }
                    });
                } else {
                    _q.resolve(obj);
                }
            },
            //请求失败
            fail: function (err) {  _q.reject(err);  },
            //请求完成后执行的函数
            complete: function () {  _q.notify(1);  }
        });
        //promis的方法有：
        //then(successCallback, errorCallback, notifyCallback)
        //finally：都会执行
        return _q.promise;
    },

    /**
     * 获取我的下线
    */
    GetDownline: function (params) {
      var apiUrl = this.getUrl('GetDownline');
      params = extend({
        Level: -1,
      }, params);
      params = this.getParams(params, true);
      return apiPost(apiUrl, params);
    },

    /**
    * 获取我的收益
    */
    GetIncome: function (params) {
      var apiUrl = this.getUrl('GetIncome');
      params = this.getParams(params, true);
      return apiPost(apiUrl, params);
    },

    /**
    * 获取我的资金
    */
    GetCash: function (params) {
      var apiUrl = this.getUrl('GetCash');
      params = this.getParams(params, true);
      return apiPost(apiUrl, params);
    },

    /**
    * 删除我的资金
    */
    DeleteCash: function (params) {
      var apiUrl = this.getUrl('DeleteCash');
      params = this.getParams(params, true);
      return apiPost(apiUrl, params);
    },

    /**
    * 获取我的提现银行
    */
    GetBank: function (params) {
      var apiUrl = this.getUrl('GetBank');
      params = this.getParams(params, true);
      return apiPost(apiUrl, params);
    },

    /**
     * 添加用户提现申请
    */
    AddWithdraw: function (params) {
      var apiUrl = this.getUrl('AddWithdraw');
      params = this.getParams(params, true);
      return apiPost(apiUrl, params);
    },

    /**
     * 设置提现密码
     */
    SetCashPassword: function (params) {
      var apiUrl = this.getUrl('SetCashPassword');
      params = this.getParams(params, true);
      return apiPost(apiUrl, params);
    },

    /**
    * 小程序充值
    */
   Recharge: function (params) {
    var _q = q.defer();
    var url = this.getUrl('Recharge');
    params = this.getParams(params, true);
    wx.request({
      url: url,
      method: "POST",
      data: params,
      header: { 'Content-Type': "application/x-www-form-urlencoded" },
      //请求成功
      success: function (r) {
        var obj = r.data;
        if (obj.Status == 1) {
          wx.requestPayment({
            'timeStamp': obj.Data['timeStamp'].toString(),
            'nonceStr': obj.Data['nonceStr'],
            'package': obj.Data['package'],
            'signType': obj.Data['signType'],
            'paySign': obj.Data['paySign'],
            'complete': function (res) {
              if (res.errMsg == "requestPayment:ok") {
                obj.Status = 1;
                obj.Message = "支付成功！"
                obj,Data = r.data.CashID;
                _q.resolve(obj);
              } else {
                obj.Status = 0;
                obj.Message = "支付失败！";
                obj.Data = r.data.CashID;
                _q.resolve(obj);
              }
            }
          });
        } else {
          _q.resolve(obj);
        }
      },
      //请求失败
      fail: function (err) { 
        _q.reject(err); 
      },
      //请求完成后执行的函数
      complete: function () { 
        _q.notify(1); 
      }
    });
    //promis的方法有：
    //then(successCallback, errorCallback, notifyCallback)
    //finally：都会执行
    return _q.promise;
  },

    //自动登录
    autoLoginWx:function(){
      var app = getApp();
      var Member = app.globalData.Member;
      //1.判断用户是否授权
      wx.getSetting({
        success: (res) => {
          if(!res.authSetting['scope.userInfo']){
            //未授权，跳转至授权页面
            wx.navigateTo({
              url: '../authorize/authorize'　　
            })
          }else if(!Member.MemberID){ //未登录
            wx.showLoading({
              title: that.data.L.LoginLoading,
            })
            api.wxLogin().then(function (r) {
              wx.hideLoading();
              if (r.Status == 1) {
                //登陆成功
                app.globalData.Member = r.Data;
                wx.setStorageSync('Token', r.Data.Token);
                that.onShow();
                wx.showToast({
                  title: '登录成功',
                })
              } else {
                //登陆失败
                app.globalData.Member = '';
                wx.setStorageSync('Token', '');
                wx.showToast({
                  title: lang.get("LoginFail"),
                  icon: 'none',
                  duration: 3000
                });
              }
            })
          }
        }
      })
    },
//----------------------------021新增------------------------------
/**
 * 添加信息
 * @param {array} params 
 */
addInfo:function(params){
  var apiUrl = this.getUrl('AddInfo');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 保存定位地址
 * @param {array} params 
 */
saveLocation:function(params){
  var apiUrl = this.getUrl('SaveLocation');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 获取消息
 * @param {array} params 
 */
getMessage:function(params){
  var apiUrl = this.getUrl('GetMessage');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 阅读消息
 * @param {string|int} id 
 */
readMessage:function(id){
  var apiUrl = this.getUrl('ReadMessage');
  let params = {id:id};
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 点赞
 * @param {array} params 
 */
clickLikes:function(params){
  var apiUrl = this.getUrl('ClickLikes');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 查询点赞
 * @param {array} params 
 */
getLikes:function(params){
  var apiUrl = this.getUrl('GetLikes');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 获取艺人
 * @param {array} params 
 */
getArtist:function(params){
  var apiUrl = this.getUrl('GetArtist');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 筛选获取信息
 * @param {array} params 
 */
searchGetInfo:function(params){
  var apiUrl = this.getUrl('SearchGetInfo');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 获取会员信息
 * @param {array} params 
 */
getMember:function(id){
  var apiUrl = this.getUrl('GetMember');
  let params = {MemberID:id};
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 场地申请 
 * @param {array} params 
 */
applyArea:function(params){
  var apiUrl = this.getUrl('ApplyArea');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 打卡
 * @param {array} params 
 */
clockIn:function(params){
  var apiUrl = this.getUrl('ClockIn');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 修改头像和会员名称
 * @param {array} params 
 */
updataMember:function(params){
  var apiUrl = this.getUrl('UpdataMember');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 查询审核情况
 * @param {array} params 
 */
getMemberStatus:function(params){
  var apiUrl = this.getUrl('GetMemberStatus');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 获取会员动态
 * @param {object} params 
 */
getDynamic:function(params){
  var apiUrl = this.getUrl('GetDynamic');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 点赞或关注
 * @param {object} params 
 */
memberLikes:function(params){
  var apiUrl = this.getUrl('MemberLikes');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 获取是否点赞或关注
 * @param {object} params 
 */
checkMemberLikes:function(params){
  var apiUrl = this.getUrl('CheckMemberLikes');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 获取关注的艺人信息
 * @param {object} params 
 */
getLikesMember:function(params){
  var apiUrl = this.getUrl('GetLikesMember');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 获取关注的活动+历史浏览活动+最新活动
 * @param {object} params 
 */
getFollowList:function(params){
  var apiUrl = this.getUrl('GetFollowList');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 获取场地
 * @param {object} params 
 */
orderChannel:function(params){
  var apiUrl = this.getUrl('OrderChannel');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 获取选择场地
 * @param {object} params 
 */
getSelectChannel:function(params){
  var apiUrl = this.getUrl('GetSelectChannel');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 获取记录
 * @param {object} params 
 */
getChannelHistory:function(params){
  var apiUrl = this.getUrl('GetChannelHistory');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 取消预约
 * @param {object} params 
 */
removeAction:function(params){
  var apiUrl = this.getUrl('RemoveAction');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 删除记录
 * @param {object} params 
 */
delAction:function(params){
  var apiUrl = this.getUrl('DelAction');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 获取最新场地
 * @param {object} params 
 */
getNewAction:function(params){
  var apiUrl = this.getUrl('GetNewAction');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
/**
 * 获取活动详情
 * @param {object} params 
 */
getShowAction:function(params){
  var apiUrl = this.getUrl('GetShowAction');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},

/**
 * 获取打赏次数
 * @param {*} params 
 */
findCash:function(params){
  var apiUrl = this.getUrl('FindCash');
  params = this.getParams(params, true);
  return apiPost(apiUrl, params);
},
 /**
   * 设置充值成功
   */
  setRecharge: function (params) {
    var apiUrl = this.getUrl('SetRecharge');
    params = this.getParams(params);
    return apiGet(apiUrl, params);
  },
  /**
   * 删除未支付订单
   */
  deleteRecharge: function (params) {
    var apiUrl = this.getUrl('DeleteRecharge');
    params = this.getParams(params);
    return apiGet(apiUrl, params);
  },
/**
     * 文件上传
     * @param {String} file 
     * @param {Array} params 
     */
    upLoad:function(file){
      var _q = q.defer()
      var url = this.getUrl('UploadImg');
      wx.uploadFile({
        url: url, //开发者服务器地址
        header: { 'Content-Type': "application/x-www-form-urlencoded" },
        filePath: file,//要上传文件资源的路径
        name: "file",//文件对应的 key，开发者在服务端可以通过这个 key 获取文件的二进制内容
        //请求成功
        success: function (r) { 
          let res = r.data;
          _q.resolve(res); 
        },
        //请求失败
        fail: function (err) { 
          console.log(err);
          _q.reject(err); 
        },
        //请求完成后执行的函数
        complete: function () { 
          console.log(1);
          _q.notify(1); 
        }
      })
      return _q.promise;
    }  
};